package cn.com.dhcc.app.pub.module.login.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.com.dhcc.app.core.base.BaseService;
import cn.com.dhcc.app.core.base.CmCommon;
import cn.com.dhcc.app.core.base.cache.CacheGroupName;
import cn.com.dhcc.app.core.base.user.LoginUser;
import cn.com.dhcc.app.core.component.db.orm.WhereCondition;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.para.CorePara.StaticPara;
import cn.com.dhcc.app.core.util.CollectionUtil;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
import cn.com.dhcc.app.pub.core.Table.SYS_BASE_TABLE;
import cn.com.dhcc.app.pub.module.authmgr.vo.RoleInfoInner;
import cn.com.dhcc.app.pub.module.login.vo.LoginCustomData;
import cn.com.dhcc.app.pub.module.resmgr.service.ResourceService;
import cn.com.dhcc.app.pub.module.resmgr.vo.LinkResource;
import cn.com.dhcc.app.pub.module.resmgr.vo.MenuResource;
import cn.com.dhcc.app.pub.module.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.pub.module.usermgr.vo.UserExt;
/**
 * 登录处理服务
 * @日期：2013-6-6下午7:13:18
 * @作者：乔兵
 */
@Component
public class LoginService extends BaseService{

	@Autowired
	private CmUserMgrService  userMgrService;
	@Autowired
	private ResourceService resourceService;
	
	public void loadUserResource(LoginUser loginUser,HttpSession httpSession) throws ServiceException, NiceException{
		if(UAMS.AUTH_RESOURCE_MANAGED){
			//将用户拥有的资源加入内存
			if(loginUser.isSuperAdmin()){
				loadAuthResource(httpSession,loginUser,true);
			}else{
				loadAuthResource(httpSession,loginUser,false);
			}
			//loginUser.setInitResIds(loginService.getUserInitResIdPath(loginUser,httpSession));
		}
	}
	/**
	 * 根据用户名，和当前用户的资源列表将资源加入缓存
	 * @param userId
	 * @param urs
	 */
	@SuppressWarnings("unchecked")
	private void loadUserResourceInToSession(HttpSession httpSession, String userId,List<Map<String, Object>> menuIds,List<Map<String, Object>> linkIds){
		Map<String, MenuResource> id_menu_resource = (Map<String,MenuResource>) CmCommon.getCacheService().getFromCacheByKey(CacheGroupName.RESOURCE_CACHE,"获取资源列表",ResourceService.CACHEED_RESOURCE_ID_MENUS_COLLECTION_KEY);
		Map<String, LinkResource> id_link_resource = (Map<String,LinkResource>) CmCommon.getCacheService().getFromCacheByKey(CacheGroupName.RESOURCE_CACHE,"获取资源列表",ResourceService.CACHEED_RESOURCE_ID_LINKS_COLLECTION_KEY);
		List<String> userActionResourceUrls = new ArrayList<String>();
		List<MenuResource> userMenuResourceUrls = new ArrayList<MenuResource>();
		List<MenuResource> userTopMenuResourceUrls = new ArrayList<MenuResource>();
		if(CollectionUtil.hasElement(menuIds)&&CollectionUtil.hasElement(id_menu_resource)){
			for (Iterator<Map<String, Object>> iterator = menuIds.iterator(); iterator.hasNext();) {
				Map<String, Object> map =  iterator.next();
				String id = (String)map.get("menu_id");
				MenuResource resource = (MenuResource) id_menu_resource.get(id.toLowerCase());
				if(resource==null)continue;
				if(ResourceService.isTopMenu(resource)){
					userTopMenuResourceUrls.add(resource);
				}
				userMenuResourceUrls.add(resource);
			}
		}
		if(CollectionUtil.hasElement(linkIds)&&CollectionUtil.hasElement(id_link_resource)){
			for (Iterator<Map<String, Object>> iterator = linkIds.iterator(); iterator.hasNext();) {
				Map<String, Object> map =  iterator.next();
				String id = (String)map.get("link_id");
				LinkResource resource = (LinkResource) id_link_resource.get(id.toLowerCase());
				if(resource==null)continue;
				userActionResourceUrls.add(resource.getUrl().toLowerCase());
			}
		}
		//所有的url 用于判断权限使用
		httpSession.setAttribute(StaticPara.USER_SESSION_URLS_KEY, userActionResourceUrls);
		//所有的菜单用于生成菜单使用
		httpSession.setAttribute(StaticPara.USER_SESSION_MENUS_KEY, userMenuResourceUrls);
		//顶部菜单
		Collections.sort(userTopMenuResourceUrls);
		httpSession.setAttribute(StaticPara.USER_SESSION_MENUS_TOP_KEY, userTopMenuResourceUrls);
	}
	/**
	 * 根据岗位编码列表获取菜单
	 * @param userId
	 * @param jonCodes
	 * @param isAdmin
	 * @throws ServiceException
	 * @throws NiceException 
	 */
	public void  loadAuthResource(HttpSession httpSession,LoginUser userInfo, boolean isAdmin) throws ServiceException, NiceException{
		
		if(UAMS.isSLUAMS()||UAMS.isSelfUser()){
			loadAuthResourceByRole(httpSession, userInfo, isAdmin);
		}else{
			//loadAuthJobResource(httpSession, userInfo, isAdmin);
		}
	}
	/**
	 * 根据岗位编码列表获取菜单
	 * @param userId
	 * @param jonCodes
	 * @param isAdmin
	 * @throws ServiceException
	 * @throws NiceException 
	 *//*
	public void  loadAuthJobResource(HttpSession httpSession,LoginUser userInfo, boolean isAdmin) throws ServiceException, NiceException{
		String userId = userInfo.getId();
		String[] jobCodes = null;
		if(!isAdmin){
			jobCodes = userInfo.getJobCodes();
		}
		if(!isAdmin&&(jobCodes==null||jobCodes.length==0)){
			throw new NiceException("当前登陆用户没有配置岗位，无法登陆");
		}
		String getMenu_sql = 
				" SELECT distinct(rrm.menu_id)  FROM " +
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_JOB_ROLE+" jr,")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_ROLE_RIGHT+" rrr")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_RIGHT_MENU+" rrm")+
				" WHERE  jr.role_id=rrr.role_id and rrr.right_id=rrm.right_id";
		String getlink_sql = 
				" SELECT distinct(l.id)  link_id FROM " +
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_JOB_ROLE+" jr,")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_ROLE_RIGHT+" rrr")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_RIGHT_MENU+" rrm")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_MENU_LINK+" rml")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_LINK+" l")+
				" WHERE  jr.role_id=rrr.role_id and rrr.right_id=rrm.right_id and rrm.menu_id=rml.menu_id and rml.link_id=l.id";
		WhereCondition parameter = new WhereCondition();
		parameter.andIn("jr.job_code", jobCodes);
		if(isAdmin){//所有
			getMenu_sql = " SELECT m.id menu_id" +
					" FROM "+WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_MENU)+" m";
			getlink_sql = " SELECT l.id link_id" +
					" FROM "+WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_LINK)+" l";
			parameter = null;
		}
		try {
			List<Map<String, Object>> menuIds = CmCommon.getDao().listMap("获取用户有权限的资源",getMenu_sql,parameter,new Object[]{});
			List<Map<String, Object>> linkIds = CmCommon.getDao().listMap("获取用户有权限的资源",getlink_sql,parameter,new Object[]{});
			if(!isAdmin&&!CollectionUtil.hasElement(menuIds)){
				throw new NiceException("当前登陆用户没有配置菜单资源，无法登陆");
			}
			if(!isAdmin&&!CollectionUtil.hasElement(linkIds)){
				throw new NiceException("当前登陆用户没有操作权限，无法登陆");
			}
			loadUserResourceInToSession(httpSession,userId, menuIds,linkIds);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}*/
	/**
	 * 从角色列表中后去角色code数组，用于数据库查询
	 * @return 角色code数组
	 */
	public String[] getRoleCodeListFromRoleInfoList(List<RoleInfoInner> roleInfoInners){
		if(CollectionUtil.hasElement(roleInfoInners)){
			String[] roleCodes = new String[roleInfoInners.size()];
			int index = 0;
			for (Iterator<RoleInfoInner> iterator = roleInfoInners.iterator(); iterator
					.hasNext();) {
				RoleInfoInner roleInfoInner = (RoleInfoInner) iterator.next();
				roleCodes[index] = roleInfoInner.getRoleCode();
				index++;
			}
			return roleCodes;
		}
		return null;
	}
	/**
	 * 根据岗位编码列表获取菜单
	 * @param userId
	 * @param jonCodes
	 * @param isAdmin
	 * @throws ServiceException
	 * @throws NiceException 
	 */
	public void  loadAuthResourceByRole(HttpSession httpSession,LoginUser userInfo, boolean isAdmin) throws ServiceException, NiceException{
		String userId = userInfo.getId();
		String[] roleCodes = null;
		if(!isAdmin){
			LoginCustomData customData = (LoginCustomData) userInfo.getCustomData();
			List<RoleInfoInner> roleInfoInners = customData.getInnerRoles();
			roleCodes = getRoleCodeListFromRoleInfoList(roleInfoInners);
		}
		if(!isAdmin&&(roleCodes==null||roleCodes.length==0)){
			throw new NiceException("当前登陆用户没有配置角色，无法登陆");
		}
		String getMenu_sql = 
				" SELECT distinct(rrm.menu_id)  FROM " +
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_ROLE+" r ,")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_ROLE_RIGHT+" rrr, ")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_RIGHT_MENU+" rrm ")+
				" WHERE r.id=rrr.role_id and   rrr.right_id=rrm.right_id";
		String getlink_sql = 
				" SELECT distinct(l.id)  link_id FROM " +
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_ROLE+" r, ")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_ROLE_RIGHT+" rrr, ")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_RIGHT_MENU+" rrm, ")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_REL_MENU_LINK+" rml, ")+
				 WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_LINK+" l")+
				" WHERE r.id=rrr.role_id and  rrr.right_id=rrm.right_id and rrm.menu_id=rml.menu_id and rml.link_id=l.id";
		WhereCondition parameter = new WhereCondition();
		parameter.andIn("r.role_code", roleCodes);
		if(isAdmin){//所有
			getMenu_sql = " SELECT m.id menu_id" +
					" FROM "+WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_MENU)+" m";
			getlink_sql = " SELECT l.id link_id" +
					" FROM "+WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_LINK)+" l";
			parameter = null;
		}
		try {
			List<Map<String, Object>> menuIds = CmCommon.getDao().listMap("获取用户有权限的菜单资源",getMenu_sql,parameter,new Object[]{});
			List<Map<String, Object>> linkIds = CmCommon.getDao().listMap("获取用户有权限的链接资源",getlink_sql,parameter,new Object[]{});
			if(!isAdmin&&!CollectionUtil.hasElement(menuIds)){
				throw new NiceException("当前登陆用户没有配置菜单资源，无法登陆");
			}
			if(!isAdmin&&!CollectionUtil.hasElement(linkIds)){
				throw new NiceException("当前登陆用户没有操作权限，无法登陆");
			}
			loadUserResourceInToSession(httpSession,userId, menuIds,linkIds);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	/**
	 * 获取用户初始化菜单路径
	 * @param userId
	 * @return
	 * @throws ServiceException
	 */
	public List<String> getUserInitResIdPath(LoginUser user,HttpSession httpSession) throws ServiceException{
		WhereCondition searchParameter = new WhereCondition();
		searchParameter.where1Eq1().andEq("USER_ID", user.getId());
		UserExt userExt = userMgrService.getUserExt(searchParameter);
		List<String> initResIdPath = new ArrayList<String>();
		if(userExt!=null&&StringUtils.hasText(userExt.getInitResourceId())){
			initResIdPath.addAll(resourceService.getResourcePath(userExt.getInitResourceId()));
		}else{
			MenuResource defaultInit = resourceService.getDefaultInitResource();
			if(defaultInit!=null){
				defaultInit = ResourceService.getMenuResourceFromCache(defaultInit.getId());
				String defaultUrl = defaultInit.getUrl();
				@SuppressWarnings("unchecked")
				List<String> userMenuResourceUrls = (List<String>) httpSession.getAttribute(StaticPara.USER_SESSION_URLS_KEY);
				if(user.isSuperAdmin()){
					initResIdPath.addAll(resourceService.getResourcePath(defaultInit.getActionId()));
				}else{
					if(StringUtils.hasText(defaultUrl)&&userMenuResourceUrls!=null&&userMenuResourceUrls.contains(defaultUrl.toLowerCase())){
						initResIdPath.addAll(resourceService.getResourcePath(defaultInit.getActionId()));
					}
				}
			}
		}
		return initResIdPath;
	}
	
}
